﻿using B.S.BasicData.Api.Read.Application.Command.Menu;
using B.S.BasicData.Api.Read.DTOS;
using B.S.BasicData.Domain.Entity;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infastructure.Interface;
using B.S.BasicData.Infastructure.Migrations;
using MediatR;

namespace B.S.BasicData.Api.Read.Application.Handler.Menu
{
    public class GetMenuHandler : IRequestHandler<GetMenuCommand, ApiPaging<MenuDto>>
    {
        private readonly IBaseRepository<PathModel> _pathRepository;

        public GetMenuHandler(IBaseRepository<PathModel> pathRepository)
        {
            _pathRepository = pathRepository;
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiPaging<MenuDto>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<MenuDto>result = new ApiPaging<MenuDto>();

            var path = _pathRepository.GetAll().Where(p => p.IsDelete == false);

            var list = (from a in path
                       join b in path on a.PartentId equals b.Id
                       select new MenuDto
                       {
                           Id= a.Id,
                           MenuName=a.MenuName,
                           Url=a.Url,
                           PartentId=a.PartentId,
                           PartMenuName=b.MenuName,
                           Orderby=a.Orderby,
                           CreateTime= a.CreateTime,
                           Creater=a.Creater,
                           Updater=a.Updater,
                           UpdateTime= a.UpdateTime,
                       }).ToList();

            result.TotalCount = list.Count();
            result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.pagesize);
            result.Code = StatusEnum.OK;
            result.PageData=list.OrderByDescending(p=>p.Orderby).Skip((request.pageindex-1)*request.pagesize).Take(request.pagesize).ToList();
            result.Message = "获取数据成功";
            return Task.FromResult(result);
        }
    }
}
